package com.example.onlinemonitoring.AOP;

import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import com.example.onlinemonitoring.model.common.MyResult;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * AuthorizationAspect
 * 鉴定访问权限
 * @author little pig page
 * @date 2021-11-04
 */
@Aspect
@Component
public class AuthorizationAspect {
//新建一个字符串卡车
    private static final Cache<String,Object> CACHE = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(1, TimeUnit.SECONDS).build();

    @Pointcut("@annotation(Authorization)")
    public void pointCut(Authorization Authorization) {
    }

    @Around("pointCut(Authorization)")
    public Object around(ProceedingJoinPoint pjp,Authorization Authorization) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();//获取属性
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);//请求属性

        // 此处可以用token或者JSessionId
        String token = request.getHeader("Authorization");//用户名
        String path = request.getServletPath();//路径
        String key = token + path;//密匙
        if(StringUtils.hasText(key)){
            if(CACHE.getIfPresent(key) != null){
                return new MyResult<Integer>(MyResult.FALSE,"请勿重复提交！");
            }
            CACHE.put(key,key);//添加一个密匙字符串
        }
        try{
            return pjp.proceed();//执行程序
        }catch (Throwable throwable){
            throw new RuntimeException("鉴定访问权限异常！");
        }finally {

        }
    }
}
